package com.tim.app.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import com.application.library.log.DLOG;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.tim.app.constant.EventTag;
import com.tim.app.server.entry.Story;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by SEELE on 2017/7/28.
 */

public class MusicService extends Service implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {

    private static final String TAG = "MusicService";

    // 常量
    public static final String MUSIC_INTENT_KEY = "storyList";
    public static final String INDEX = "index";
    // 音乐列表
    private List<Story> storyList = null;
    private int currentIndex = -1;
    private int mmSize = 0;
    private Story story = null;

    // MediaPlay
    private MediaPlayer mediaPlayer = null;
    private int currentTime = 0;

    private Timer mTimer = new Timer(); // 计时器

    @Override
    public void onCreate() {
        DLOG.e(TAG, "onCreate");
        // 初始化MediaPlay : 设置监听事件
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);

        registEvent();
        // 每一秒触发一次
        mTimer.schedule(timerTask, 0, 1000);
        super.onCreate();
    }

    /**
     * 注册事件
     */
    private void registEvent() {
        EventManager.ins().registListener(EventTag.GO_PREVIOUS, eventListener);
        EventManager.ins().registListener(EventTag.GO_NEXT, eventListener);
        EventManager.ins().registListener(EventTag.GO_PLAY_OR_PAUSE, eventListener);
        EventManager.ins().registListener(EventTag.GO_INDEX, eventListener);
        EventManager.ins().registListener(EventTag.GO_PROCESS, eventListener);
        EventManager.ins().registListener(EventTag.ON_GET_CURRENT_PLAY, eventListener);
        EventManager.ins().registListener(EventTag.ON_GET_PLAY_STATED, eventListener);
        EventManager.ins().registListener(EventTag.ON_GOTO_CURRENT_PLAY, eventListener);
    }

    /**
     * 取消注册
     */
    private void unregistEvent() {
        EventManager.ins().removeListener(EventTag.GO_PREVIOUS, eventListener);
        EventManager.ins().removeListener(EventTag.GO_NEXT, eventListener);
        EventManager.ins().removeListener(EventTag.GO_PLAY_OR_PAUSE, eventListener);
        EventManager.ins().removeListener(EventTag.GO_INDEX, eventListener);
        EventManager.ins().removeListener(EventTag.GO_PROCESS, eventListener);
        EventManager.ins().removeListener(EventTag.ON_GET_CURRENT_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_GOTO_CURRENT_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_GET_PLAY_STATED, eventListener);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.GO_PREVIOUS:
                    preSong();
                    break;
                case EventTag.GO_NEXT:
                    nextSong();
                    break;
                case EventTag.GO_PLAY_OR_PAUSE:
                    playSong();
                    break;
                case EventTag.GO_INDEX:
                    int index = (int) dataobj;
                    playSongByPositon(index);
                    break;
                case EventTag.GO_PROCESS:
                    int process = arg1;
                    int value = mediaPlayer.getDuration() * process / 100;
                    mediaPlayer.seekTo(value);
                    break;
                case EventTag.ON_GET_CURRENT_PLAY:
                    int stated = 0;
                    if (mediaPlayer.isPlaying()) {
                        stated = 1;
                    }
                    EventManager.ins().sendEvent(EventTag.GET_CURRENT_PLAY, currentIndex, stated, storyList);
                    break;
                case EventTag.ON_GOTO_CURRENT_PLAY:
                    int playStated = 0;
                    if (mediaPlayer.isPlaying()) {
                        playStated = 1;
                    }
                    EventManager.ins().sendEvent(EventTag.GET_GOTO_CURRENT_PLAY_DETAIL, currentIndex, playStated, storyList);
                    break;
                case EventTag.ON_GET_PLAY_STATED:
                    EventManager.ins().sendEvent(EventTag.GET_PLAY_STATED, 0, 0, mediaPlayer.isPlaying());
                    break;
            }
        }
    };

    // 计时器
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            try {
                if (mediaPlayer.isPlaying()) {
                    handler.sendEmptyMessage(0); // 发送消息
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (null != mediaPlayer && isPrepared) {
                int position = mediaPlayer.getCurrentPosition();
                int duration = mediaPlayer.getDuration();
                if (position > 0) {
                    EventManager.ins().sendEvent(EventTag.ON_PLAY_PROCESS_CHANGED, position, duration, null);
                }
            }
        }

    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {

            List<Story> dataList = (List<Story>) intent
                    .getSerializableExtra(MUSIC_INTENT_KEY);
            int newIndex = intent.getIntExtra(INDEX, 0);
            storyList = dataList;
            if (storyList != null) {
                mmSize = storyList.size();
            }
            DLOG.e(TAG, "onStartCommand");
            currentIndex = newIndex;
            if (null != story && dataList.get(newIndex).getId().equals(story.getId())) {
                story = storyList.get(currentIndex);
                if (mediaPlayer.isPlaying()) {
                    EventManager.ins().sendEvent(EventTag.SEND_CURRENT_STORY_PLAYING, 0, 0, story);
                } else {
                    resume();
                }
            } else {
                story = storyList.get(currentIndex);
                playSongByPositon(currentIndex);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            storyList = null;
        }
        unregistEvent();
    }


    // 音乐播放
    private void play(String musicUrl) {
        mediaPlayer.reset();
        try {
            if (!TextUtils.isEmpty(musicUrl)) {
                mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(musicUrl));
                mediaPlayer.prepareAsync();
                EventManager.ins().sendEvent(EventTag.ON_PLAY, 0, 0, null);
            }
        } catch (IOException e) {
            DLOG.e(TAG, "网络错误,播放失败");
        }
    }

    // 音乐暂停
    private void pause() {
        if (mediaPlayer.isPlaying()) {
            currentTime = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
        }
        EventManager.ins().sendEvent(EventTag.GET_PLAY_STATED, 0, 0, mediaPlayer.isPlaying());
        EventManager.ins().sendEvent(EventTag.ON_PAUSE, 0, 0, null);
    }

    // 音乐继续播放
    private void resume() {
        mediaPlayer.start();
        if (currentTime > 0) {
            mediaPlayer.seekTo(currentTime);
        }
        EventManager.ins().sendEvent(EventTag.GET_PLAY_STATED, 0, 0, mediaPlayer.isPlaying());
        EventManager.ins().sendEvent(EventTag.ON_PLAY, 0, 0, null);
    }

    // 音乐停止
    private void stop() {
        mediaPlayer.stop();
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            DLOG.e(TAG, "音乐停止异常");
        }
    }

    // //////////////////////////////Music MediaPlayListener////////////

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // 出错的时候
        DLOG.e(TAG, "onError==what==" + what + "===extra==" + extra);
        EventManager.ins().sendEvent(EventTag.ON_STOP, 0, 0, null);
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        DLOG.e(TAG, "onCompletion");
        // 播放完毕的时候
        currentTime = 0;
        EventManager.ins().sendEvent(EventTag.ON_COMPLETE, 0, 0, null);
        nextSong();
    }

    boolean isPrepared = false;

    @Override
    public void onPrepared(MediaPlayer mp) {
        // 准备加载的时候
        isPrepared = true;
        resume();
        DLOG.e(TAG, "onPrepared====");
    }

    /**
     * 播放
     */
    private void playSong() {
        if (mediaPlayer.isPlaying()) {
            pause();
        } else {
            if (currentTime > 0) {
                resume();
            } else {
                if (story != null) {
                    play(story.getAudioUrl());
                }
            }
        }
    }

    /**
     * 下一曲
     */
    private void nextSong() {
        currentTime = 0;
        if (currentIndex < 0) {
            currentIndex = 0;
        }
        if (mmSize > 0) {
            if (currentIndex < mmSize - 1) {
                currentIndex++;
                // 不超过长度
                story = storyList.get(currentIndex);
                play(story.getAudioUrl());
            } else {
                if (mmSize != 1) {
                    // 超过长度 播放第一首
                    story = storyList.get(0);
                    play(story.getAudioUrl());
                }
            }
        }
    }

    /**
     * 播放指定位置的
     *
     * @param index
     */
    private void playSongByPositon(int index) {
        currentTime = 0;
        if (currentIndex < 0) {
            currentIndex = 0;
        }
        if (mmSize > 0 && index < mmSize) {
            currentIndex = index;
            if (currentIndex < mmSize) {
                // 不超过长度
                story = storyList.get(currentIndex);
                play(story.getAudioUrl());
            } else {
//                // 超过长度 播放第一首
                story = storyList.get(0);
                play(story.getAudioUrl());
            }
        }
    }

    /**
     * 上一曲
     */
    private void preSong() {
        currentTime = 0;
        if (currentIndex < 0) {
            currentIndex = 0;
        }
        if (mmSize > 0) {
            currentIndex--;
            if (currentIndex >= 0) {
                //不小于0
                story = storyList.get(currentIndex);
                play(story.getAudioUrl());
            } else {
                // 超过长度 播放第一首，小于0 ,播放第一首
                story = storyList.get(0);
                play(story.getAudioUrl());
            }
        }
    }


}
